﻿#include "mainwindow.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLayoutItem>
#include <QDebug>
#include <QSettings>
#include <gsettingmonitor.h>
#include <QDesktopWidget>
#include <QScreen>
#include <QIcon>
#include <QPixmap>
#include "tipwidget.h"
#include "generatetools.h"
#include "config.h"

#define KYLIN_CONNECTIVITY_MANAGER_PATH "/"
#define KYLIN_CONNECTIVITY_MANAGER_SERVICE "com.kylin.connectivity.manager"
#define KYLIN_CONNECTIVITY_MANAGER_INTERFACE "com.kylin.connectivity.manager"
const QString DISC_SERVER_PATH = "/opt/kylin-connectivity/mobile_softbus_server";
const QString DISC_CLIENT_PATH = "/opt/kylin-connectivity/mobile_softbus_client";
const QString FILE_DOWN_PATH = getenv("HOME") + QString("/.connectivitycache/cache/");
const QString TEMP_DOWN_PATH = "/temp/";
const QString FILE_PATH_PCSEARCH = QString("/.connectivitycache/pcsearchInfo.db");

const int USBPORT = 27183;
const int WIFIPORT = 27186;
const int USB_FTP_PORT = 27184;
const int WIFI_FTP_PORT = 27187;
const int FTP_SERVER_PORT = 27189;
const QString USB_FTPURL = "127.0.0.1";
const QString LOCAL_ROOT = getenv("HOME") + QString("/");
const int FTP_MAX_THREAD = 5;
const int SIDE_MARGIN = 70;
const int MSGICON_H = 24;
const int MSGICON_W = 24;

MainWindow *MainWindow::getInstance()
{
    static MainWindow instance;
    return &instance;
}

QString MainWindow::getDeviceName()
{
    return m_connectInfo.deviceName;
}

void MainWindow::list(QString path)
{
    if (!m_isDbusOperation) {
        // 手机存储埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
        qInfo() << "External request file list information.";
        m_isDbusOperation = true;
        m_ftpClient->list(path);
    }
}

void MainWindow::downFile(const QList<FileInfo> &fileList, QString downloadPath)
{
    if (!m_isDbusOperation) {
        // 下载文件埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
        qInfo() << "External requests to download the file.";
        m_isDbusOperation = true;
        m_ftpClient->downAllFiles(fileList, downloadPath);
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    this->hide();
    if (m_isConnect) {
        slotDisconnect();
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_F1) {
        m_titlebar->initHelp();
    }
    // else if (event->key() == Qt::Key_H && event->modifiers() == Qt::ControlModifier) {
    //     m_suspendTabBar->setControlState(true);
    //     m_pcScreen->startedControl();
    //     m_suspendTabBar->hide();
    // } else if (event->key() == Qt::Key_G && event->modifiers() == Qt::ControlModifier) {
    //     m_suspendTabBar->setControlState(false);
    //     m_pcScreen->exitControl();
    //     m_suspendTabBar->show();
    // }
    QWidget::keyPressEvent(event);
}

MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
    qRegisterMetaType<QMap<QString, FileInfo>>("QMap<QString,FileInfo>");
    initUI();
    initService();
    initGsetting();
    initDbus();
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    qDebug() << this->x() << "          " << this->y();
    Q_UNUSED(event);
    if (m_listItemWidget) {
        m_listItemWidget->setViewHeight();
    }
    if (m_mobileStorageWidget) {
        m_mobileStorageWidget->setViewHeight();
    }
    if (m_connectInterfaceWin != nullptr) {
        m_connectInterfaceWin->moveSearchBtn();
    }
}

MainWindow::~MainWindow()
{
    deleterUI();
    deleterService();
}

void MainWindow::initService()
{
    m_connectionService = new ConnectionService(this);
    QStringList list;
    GenerateTools::getUserPassword(list);
    m_connectionService->setUserPassword(list.value(GenerateTools::KEY_USERPASS::KEY_USER),
                                         list.value(GenerateTools::KEY_USERPASS::KEY_PASSWORD));
    connect(m_connectionService, &ConnectionService::sigConnectRequest, this, &MainWindow::slotConnectRequest);
    connect(m_connectionService, &ConnectionService::sigConnectDenied, this, &MainWindow::slotConnectDenied);
    connect(m_connectionService, &ConnectionService::sigConnectInfo, this, &MainWindow::slotConnect);
    connect(m_connectionService, &ConnectionService::sigDisconnect, this, &MainWindow::slotDisconnect);
    connect(m_connectionService, &ConnectionService::sigNotFountApk, this, &MainWindow::slotNotFountApk);

    // 监听USB插拔信号
    m_usbManage = new UsbManage;
    connect(m_usbManage, &UsbManage::sigVolumeConnected, this, &MainWindow::slotVolumeConnected);
    connect(m_usbManage, &UsbManage::sigVolumeDisconnected, this, &MainWindow::slotVolumeDisconnected);

    // 监听wifi
    m_wifiManager = new WifiManager;
    connect(m_wifiManager, &WifiManager::sigWifiConnected, this, &MainWindow::slotWifiConnected);
    connect(m_wifiManager, &WifiManager::sigWifiDisconnected, this, &MainWindow::slotWifiDisConnected);

    m_wifiManagerThread = new QThread;
    m_wifiManager->moveToThread(m_wifiManagerThread);

    connect(m_wifiManagerThread, &QThread::started, m_wifiManager, &WifiManager::startWifiInfo);

    m_wifiManagerThread->start();

    m_dirManager = new DirManager;
    connect(m_dirManager, &DirManager::finish, m_dirManager, &DirManager::deleteLater);
    m_dirManager->start();

    // 启动ftp服务端
    m_ftpServer = new FtpServer(FTP_SERVER_PORT);
    m_ftpServer->addUser(list.value(GenerateTools::KEY_USERPASS::KEY_USER).toStdString(),
                         list.value(GenerateTools::KEY_USERPASS::KEY_PASSWORD).toStdString(), LOCAL_ROOT.toStdString(),
                         fineftp::Permission::All);
    m_ftpServer->start(FTP_MAX_THREAD);

    m_pcScreen = new PcScreenManage;
    connect(m_pcScreen, &PcScreenManage::sigRequestReceived, this, &MainWindow::slotRequestReceived);

    m_dbusInterface = new QDBusInterface(KYLIN_CONNECTIVITY_MANAGER_SERVICE, KYLIN_CONNECTIVITY_MANAGER_PATH,
                                         KYLIN_CONNECTIVITY_MANAGER_INTERFACE, QDBusConnection::systemBus());
    QObject::connect(m_dbusInterface, SIGNAL(sigMountError(bool, QString)), this, SLOT(slotMountError(bool, QString)));
    QObject::connect(m_dbusInterface, SIGNAL(sigInitDiscServer(bool)), this, SLOT(slotInitDiscServerResult(bool)));
    discInit();
}

void MainWindow::initGsetting(void)
{
    /* 主题 */
    QString themeStr = kdk::GsettingMonitor::getSystemTheme().toString();
    if (themeStr == QString("ukui-dark") || themeStr == QString("ukui-black")) {
        changeDarkTheme();
    } else {
        changeLightTheme();
    }
    connect(kdk::GsettingMonitor::getInstance(), &kdk::GsettingMonitor::systemThemeChange, this, [=]() {
        QString themeStr = kdk::GsettingMonitor::getSystemTheme().toString();
        if (themeStr == QString("ukui-dark") || themeStr == QString("ukui-black")) {
            changeDarkTheme();
        } else {
            changeLightTheme();
        }
    });

    return;
}

void MainWindow::initDbus()
{
    QDBusConnection sessionBus = QDBusConnection::sessionBus();
    if (!sessionBus.registerService(KYLIN_CONNECTIVITY_SEND_SERVICE)) {
        qInfo() << "init dbus fail...";
        return;
    }
    sessionBus.registerObject(KYLIN_CONNECTIVITY_SEND_PATH, this, QDBusConnection::ExportAllSlots);
}

void MainWindow::disconnectScreen()
{
    // 断开连接
    if (m_deviceManage != nullptr) {
        // 清空设备名
        delete m_deviceManage;
        m_deviceManage = nullptr;
    }
    if (m_pcScreen != nullptr) {
        m_pcScreen->disconnected();
    }
}

void MainWindow::disconnectFtp()
{
    if (m_ftpClient != nullptr) {
        if (m_isMountFtp) {
            umountFtp(MOUNT_DIR);
            m_isMountFtp = false;
        }
        delete m_ftpClient;
        m_ftpClient = nullptr;
    }
}

void MainWindow::stopAllDown()
{
    if (m_fileSyncManage != nullptr) {
        m_fileSyncManage->abortDown();
        delete m_fileSyncManage;
        m_fileSyncManage = nullptr;
    }
}

void MainWindow::disconnectService()
{
    stopAllDown();
    disconnectScreen();
    disconnectFtp();
    if (m_connectionService != nullptr) {
        m_connectionService->abortService();
    }
    m_isServerConnect = false;
}

void MainWindow::deleterService()
{
    if (m_usbManage != nullptr) {
        m_usbManage->deleteLater();
        m_usbManage = nullptr;
    }
    if (m_wifiManager != nullptr) {
        m_wifiManager->deleteLater();
        m_wifiManager = nullptr;
    }
    if (m_wifiManagerThread != nullptr) {
        m_wifiManagerThread->quit();
        m_wifiManagerThread->wait();
        m_wifiManagerThread->deleteLater();
        m_wifiManagerThread = nullptr;
    }
    if (m_ftpServer != nullptr) {
        m_ftpServer->stop();
        delete m_ftpServer;
        m_ftpServer = nullptr;
    }
    if (m_pcScreen != nullptr) {
        m_pcScreen->deleteLater();
        m_pcScreen = nullptr;
    }
    if (m_dbusInterface != nullptr) {
        deInitDisc();
        if (m_dbusInterface->isValid()) {
            m_dbusInterface->call("killServerPortProcess");
        }
    }
}

bool MainWindow::mountFtp(QString url, QString userName, QString pwd, QString path)
{
    if (m_dbusInterface->isValid()) {
        qInfo() << "Start mounting FTP...";
        m_dbusInterface->call("mountFtp", url, userName, pwd, path);
        return true;
    }
    return false;
}

bool MainWindow::umountFtp(QString path)
{
    if (m_dbusInterface->isValid()) {
        qInfo() << "Start umounting FTP...";
        m_dbusInterface->call("umountFtp", path);
        return true;
    }
    return false;
}

void MainWindow::clearConnectionInfo()
{
    m_connectInfo.uuid.clear();
    m_connectInfo.deviceName.clear();
    m_connectInfo.address.clear();
    m_connectInfo.connectType = ConnectionService::ConnectType::NOTCONNECT;
    m_connectInfo.usernamePwd.username.clear();
    m_connectInfo.usernamePwd.pwd.clear();
}

void MainWindow::changeLightTheme()
{
    m_theme = PublicAttributes::Theme::Light;
    qInfo() << "changeLightTheme";
    if (m_titlebar != nullptr) {
        m_titlebar->setTheme(m_theme);
    }
    if (m_connectInterfaceWin != nullptr) {
        m_connectInterfaceWin->setTheme(m_theme);
    }
    if (m_connectedWin != nullptr) {
        m_connectedWin->setTheme(m_theme);
    }
    if (m_suspendTabBar != nullptr) {
        m_suspendTabBar->setTheme(m_theme);
    }
}

void MainWindow::changeDarkTheme()
{
    m_theme = PublicAttributes::Theme::Dark;
    qInfo() << "changeDarkTheme";
    if (m_titlebar != nullptr) {
        m_titlebar->setTheme(m_theme);
    }
    if (m_connectInterfaceWin != nullptr) {
        m_connectInterfaceWin->setTheme(m_theme);
    }
    if (m_connectedWin != nullptr) {
        m_connectedWin->setTheme(m_theme);
    }
    if (m_suspendTabBar != nullptr) {
        m_suspendTabBar->setTheme(m_theme);
    }
}

void MainWindow::initUI()
{
    setMinimumSize(1024, 680);
    setWindowTitle(tr("kylin-connectivity"));

    m_titlebar = new Titlebar(this);
    connect(m_titlebar, &Titlebar::sigAboutWinShow, this, &MainWindow::slotAboutWinShow);
    connect(m_titlebar, &Titlebar::sigSearchResult, this, &MainWindow::onRecvSearchResult);
    connect(m_titlebar, &Titlebar::sigSearchInitFail, this, &MainWindow::slotSearchInitFail);
    connect(this, &MainWindow::sigClearSearchLine, m_titlebar, &Titlebar::onBackButtonClick);

    m_homepage = new HomePage;
    m_homepage->setDeviceCode(m_wifiIp);
    connect(m_homepage, &HomePage::sigConnectBtnClicked, this, &MainWindow::slotConnectBtnClicked);

    m_connectInterfaceWin = new ConnectInterface;
    connect(m_connectInterfaceWin, &ConnectInterface::sigUSBconnectBtnClicked, this,
            &MainWindow::slotUSBConnectOnClicked);
    connect(m_connectInterfaceWin, &ConnectInterface::sigBackBtnClicked, this, &MainWindow::slotReturnHomePage);
    connect(m_connectInterfaceWin, &ConnectInterface::sigConnectAddress, this, &MainWindow::slotConnectServiceUI);
    connect(m_connectInterfaceWin, &ConnectInterface::sigContinueSearch, this, &MainWindow::slotContinueSearch);

    m_connectInterfaceWin->setInterFaceCodeInfo(m_wifiIp);

    m_mainStackedWin = new QStackedWidget(this);
    m_mainStackedWin->addWidget(m_homepage);
    m_mainStackedWin->setCurrentIndex(WinIndex::WinHomePage);
    m_mainStackedWin->addWidget(m_connectInterfaceWin);

    QHBoxLayout *hLayout2 = new QHBoxLayout;
    hLayout2->setSpacing(0);
    hLayout2->setMargin(0);
    hLayout2->addWidget(m_mainStackedWin);

    QVBoxLayout *vLayout = new QVBoxLayout;
    vLayout->setSpacing(0);
    vLayout->setMargin(0);
    vLayout->addWidget(m_titlebar);
    vLayout->addLayout(hLayout2);

    this->setLayout(vLayout);
    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);
}

void MainWindow::connectUI()
{
    if (!m_isConnect) {
        m_isConnect = true;
        m_connectedWin = new ConnectedWin;
        m_stackedMobileFileListWin = new QStackedWidget(this);
        m_connectedWin->addWidget(m_stackedMobileFileListWin);
        connect(m_connectedWin, &ConnectedWin::sigBtnClicked, this, &MainWindow::slotConnectedWinBtnClicked);
        m_connectedWin->setDeviceName(m_connectInfo.deviceName);
        if (m_connectInfo.deviceType == ConnectionService::DeviceType::PC) {
            m_connectedWin->setDeviceType(PublicAttributes::DeviceType::Pc);
            if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::INITIATOR) {
                m_connectedWin->changeScreenButton(false);
            } else if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::RECIPIENT) {
                m_connectedWin->changeScreenButton(true);
            }
        } else if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
            m_connectedWin->setDeviceType(PublicAttributes::DeviceType::Android);
        }
        m_mainStackedWin->addWidget(m_connectedWin);

        stopLoadUI();

        // m_discovery->stopDiscovery();

        QString str1 = "";
        if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::INITIATOR) {
            str1 = QString(tr("Agreed to connect"));
        } else {
            str1 = QString(tr("Peer has agreed"));
        }
        QString str2 = QString(tr("Establishing connection, please wait..."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(tr("CANCEL"), QMessageBox::RejectRole);
        connect(m_messageBox, &QMessageBox::buttonClicked, this, [=](QAbstractButton *) {
            slotDisconnect();
            stopLoadUI();
        });
        m_messageBox->show();
        startTimer();
    }
    m_currentPath = "Home page";
}

void MainWindow::updateResult()
{
    stopLoadUI();
    if (m_winFlage == WinFlage::DisconnectWin) {
        m_titlebar->setBackground(false);
        m_mainStackedWin->setCurrentIndex(WinIndex::WinConnected);
        m_connectInterfaceWin->setSearchBtnState(false);
        m_winFlage = WinFlage::SyncMainWin;
        if (m_connectInfo.connectType == ConnectionService::ConnectType::USB) {
            QString str1 = QString(tr("USB connection device succeeded!"));
            QString str2 = QString(
                tr("If you need to input Chinese on the mobile phone screen on the computer, please download the "
                   "extension tool in the personal information input method on the mobile phone."));
            m_messageBox = new QMessageBox(this);
            m_messageBox->setText(str1 + "\n" + str2);
            m_messageBox->setIconPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(MSGICON_W, MSGICON_H));
            m_messageBox->addButton(tr("OK"), QMessageBox::RejectRole);
            m_messageBox->show();
        }
    }
    if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
        if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_FILE_NUM) {
            QMap<QString, int> fileNumMap;
            m_fileSyncManage->getItemCount(fileNumMap);
            if (m_mobileFileList == nullptr) {
                m_mobileFileList = new MobileFileList();
                connectMobileFileList();
                m_mobileFileList->setItemCount(fileNumMap);
                m_mobileFileList->setTheme(m_theme);
                m_stackedMobileFileListWin->addWidget(m_mobileFileList);
                m_stackedMobileFileListWin->setCurrentIndex(0);
            }
            if (m_winFlage == WinFlage::SyncQQWechatWin) {
                m_mobileFileSecondWidget->setItemCount(fileNumMap);
                m_stackedMobileFileListWin->setCurrentIndex(1);
                m_loadAnimation->deleteLater();
                m_loadAnimation = nullptr;
            }
            if (m_winFlage == WinFlage::SyncMainWin) {
                m_loadAnimation->deleteLater();
                m_loadAnimation = nullptr;
            }
        } else {
            QList<FileInfo> list;
            m_fileSyncManage->getClassifiedFileList(m_downFileType, list);
            if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_MUSIC
                || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_MUSIC
                || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_MUSIC) {
                m_listItemWidget->setMusicData(list);
            } else if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_DOCUMENT
                       || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_DOCUMENT
                       || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_DOCUMENT) {
                m_listItemWidget->setDocumenData(list);
            } else {
                m_listItemWidget->setTimeLineData(list);
            }
        }
    }
}

void MainWindow::initTransmissionDialog()
{
    m_transmissionDialog = new TransmissionDialog(this);
    connect(m_transmissionDialog, &TransmissionDialog::sigCancelAbort, this, &MainWindow::slotAbortTransmission);
    QRect availableGeometry = geometry();
    m_transmissionDialog->move(availableGeometry.center() - m_transmissionDialog->rect().center());
    m_transmissionDialog->show();
}

void MainWindow::deleteMobileListWidget()
{
    stopLoadUI();
    if (m_mobileStorageWidget != nullptr) {
        m_mobileStorageWidget->deleteLater();
        m_mobileStorageWidget = nullptr;
    }
    if (m_listItemWidget != nullptr) {
        m_listItemWidget->deleteLater();
        m_listItemWidget = nullptr;
    }
    if (m_mobileFileSecondWidget != nullptr) {
        m_mobileFileSecondWidget->deleteLater();
        m_mobileFileSecondWidget = nullptr;
    }
    if (m_loadAnimation != nullptr) {
        m_loadAnimation->deleteLater();
        m_loadAnimation = nullptr;
    }
}

void MainWindow::initMobileListWidget(int tag)
{
    qInfo() << "current index and widget :" << m_stackedMobileFileListWin->currentIndex()
            << m_stackedMobileFileListWin->currentWidget();

    for (int i = 0; i < m_stackedMobileFileListWin->count(); i++) {
        qInfo() << "all widget :" << m_stackedMobileFileListWin->count() << m_stackedMobileFileListWin->widget(i);
    }

    int index = m_stackedMobileFileListWin->currentIndex();
    m_listItemWidget = new MobileFileWidget(tag);
    m_listItemWidget->setTheme(m_theme);
    connectMobileFileWidget();
    m_stackedMobileFileListWin->addWidget(m_listItemWidget);
    m_stackedMobileFileListWin->setCurrentIndex(index + 1);
    m_listItemWidget->showLoadWin();
    m_fileSyncManage->updateFileInfo(m_downFileType);
}

void MainWindow::connectMobileFileWidget()
{
    connect(m_listItemWidget, &MobileFileWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
        m_classificationMode = mode;
    });
    connect(m_listItemWidget, &MobileFileWidget::sigInitFinish, this, &MainWindow::slotDownThumb);
    connect(m_listItemWidget, &MobileFileWidget::sigUpdateClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_listItemWidget, &MobileFileWidget::sigMenuFilePath, this, &MainWindow::slotMenuFilePath);
    connect(m_listItemWidget, &MobileFileWidget::sigShowMobileFileListWidget, this,
            &MainWindow::slotShowMobileFileListWidget);
    connect(m_listItemWidget, &MobileFileWidget::sigShowMobileFileSecondWidget, this,
            &MainWindow::slotShowMobileFileSecondWidget);
}


void MainWindow::setToolTipWin(QString msg, kdk::TipType type)
{
    kdk::KBallonTip *tipWin = new kdk::KBallonTip(this);
    tipWin->setWindowFlag(Qt::FramelessWindowHint);
    tipWin->setAttribute(Qt::WA_TranslucentBackground);
    tipWin->setTipType(type);
    tipWin->setText(msg);
    tipWin->setTipTime(2000);
    tipWin->setContentsMargins(4, 4, 8, 4);
    tipWin->move(((this->width() - tipWin->width()) >> 1) - 50, ((this->height() - tipWin->height()) >> 1) + 250);
    tipWin->showInfo();
}

void MainWindow::setLocalPathList(const QStringList &list)
{
    qInfo() << "get local peony menu send path list" << list;
    if (!m_isConnect) {
        TipWidget *tipWidget = new TipWidget();
        tipWidget->setParent(m_connectInterfaceWin);
        tipWidget->SetMesseage(tr("Not currently connected, please connect"), nullptr, 20);
        qInfo() << "peony menu send: not current connect";
        return;
    }
    uploadLocalListPath("/Download", list);
}

void MainWindow::deleterUI()
{
    if (m_titlebar != nullptr) {
        delete m_titlebar;
        m_titlebar = nullptr;
    }
    if (m_connectInterfaceWin != nullptr) {
        delete m_connectInterfaceWin;
        m_connectInterfaceWin = nullptr;
    }
    if (m_homepage != nullptr) {
        delete m_homepage;
        // system(common.toStdString().c_str());
        m_homepage = nullptr;
    }
    if (m_mobileFileList != nullptr) {
        delete m_mobileFileList;
        m_mobileFileList = nullptr;
    }
    if (m_mainStackedWin != nullptr) {
        m_mainStackedWin->deleteLater();
        m_mainStackedWin = nullptr;
    }
    stopLoadUI();
}

void MainWindow::startLoadUI()
{
    m_loadDialog = new LoadDialog(this);
    m_loadDialog->move((this->width() - m_loadDialog->width()) >> 1, ((this->height() - m_loadDialog->height()) >> 1));
    m_loadDialog->show();
    startTimer();
}

void MainWindow::startTimer()
{
    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    connect(m_timer, &QTimer::timeout, this, &MainWindow::slotConnectFailed, Qt::DirectConnection);
    m_timer->start(20000);
}

void MainWindow::stopLoadUI()
{
    if (m_loadDialog != nullptr) {
        m_loadDialog->deleteLater();
        m_loadDialog = nullptr;
    }
    if (m_messageBox != nullptr) {
        m_messageBox->hide();
        m_messageBox->deleteLater();
        m_messageBox = nullptr;
    }
    if (m_timer != nullptr) {
        m_timer->stop();
        m_timer->deleteLater();
        m_timer = nullptr;
    }
    if (m_transmissionDialog != nullptr) {
        m_transmissionDialog->deleteLater();
        m_transmissionDialog = nullptr;
        setToolTipWin(tr("file download failed"), kdk::TipType::Error);
    }
}

void MainWindow::slotVolumeConnected(QString volumeName)
{
    // todo
}

void MainWindow::slotVolumeDisconnected(QString volumeName)
{
    if (m_connectInfo.connectType == ConnectionService::ConnectType::USB && m_connectInfo.deviceName.isEmpty()) {
        qInfo() << m_connectInfo.deviceName << "disconnected";
        slotDisconnect();
    }
}

void MainWindow::slotWifiConnected(QString wifiIP)
{
    m_wifiIp = wifiIP;
    if (m_connectInterfaceWin != nullptr) {
        m_connectInterfaceWin->setInterFaceCodeInfo(wifiIP);
    }
    if (m_homepage != nullptr) {
        m_homepage->setDeviceCode(GenerateTools::getIptoCode(m_wifiIp));
    }
}

void MainWindow::slotWifiDisConnected()
{
    m_wifiIp.clear();
    if (m_connectInterfaceWin != nullptr) {
        m_connectInterfaceWin->setInterFaceCodeInfo(m_wifiIp);
    }
    if (m_homepage != nullptr) {
        m_homepage->setDeviceCode(GenerateTools::getIptoCode(m_wifiIp));
    }
    if (m_connectInfo.connectType == ConnectionService::ConnectType::WIFI) {
        slotDisconnect();
    }
}

void MainWindow::slotConnectRequest(QString deviceName, ConnectionService::DeviceType deviceType)
{
    QString str1 = QString(tr("Connection request received from\"")) + deviceName + QString(tr("\""));
    QString str2 = QString(tr("After consent, the other party can view and download all the files on the device, "
                              "and can share the other party's desktop to this screen."));
    m_messageBox = new QMessageBox(this);
    m_messageBox->setText(str1 + "\n" + str2);
    m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-warning").pixmap(MSGICON_W, MSGICON_H));
    QPushButton *noBtn = m_messageBox->addButton(QString(tr("NO")), QMessageBox::RejectRole);
    QPushButton *yesBtn = m_messageBox->addButton(QString(tr("YES")), QMessageBox::AcceptRole);
    connect(m_messageBox, &QMessageBox::buttonClicked, this, [=](QAbstractButton *btn) {
        if (yesBtn == btn) {
            m_connectionService->setConnectionRespond(true);
        } else {
            m_connectionService->setConnectionRespond(false);
        }
        stopLoadUI();
    });
    m_messageBox->show();
    startTimer();
}

void MainWindow::slotConnectDenied()
{
    QString str1 = QString(tr("The other party has refused your screen projection request!"));
    QString str2 = QString(tr("Failed to cast the screen. Please contact the other party and try again."));
    m_messageBox = new QMessageBox(this);
    m_messageBox->setText(str1 + "\n" + str2);
    m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-error").pixmap(MSGICON_W, MSGICON_H));
    QPushButton *reconnectBtn = m_messageBox->addButton(QString(tr("RECONNECT")), QMessageBox::AcceptRole);
    QPushButton *closeBtn = m_messageBox->addButton(QString(tr("CLOSE")), QMessageBox::RejectRole);
    connect(m_messageBox, &QMessageBox::buttonClicked, this, [=](QAbstractButton *btn) {
        if (reconnectBtn == btn) {
            m_connectionService->startClient(m_reconnectAddress);
        }
        stopLoadUI();
    });
    m_messageBox->show();
}

void MainWindow::slotConnect(const ConnectionService::ConnectionInfo &connectInfo)
{
    m_connectInfo = connectInfo;
    m_url.setUserName(m_connectInfo.usernamePwd.username);
    m_url.setPassword(m_connectInfo.usernamePwd.pwd);
    m_connectInfo.deviceName.remove(" ");
    connectUI();
    m_ftpClient = new FtpManager(this);
    connect(m_ftpClient, &FtpManager::sigFtpServerConnected, this, &MainWindow::slotFtpConnected);
    connect(m_ftpClient, &FtpManager::sigFtpConnectFailed, this, &MainWindow::slotConnectFailed);
    connect(m_ftpClient, &FtpManager::sigUpdateTransferProgress, this, &MainWindow::slotTransferProgress);
    connect(m_ftpClient, &FtpManager::sigCurrentDirectoryList, this, &MainWindow::slotCurrentDirectoryList);
    connect(m_ftpClient, SIGNAL(sigDownFileFail(QString)), this, SLOT(slotDownFileFail(QString)));
    connect(m_ftpClient, &FtpManager::sigFtpReconnected, this, [=]() {
        stopLoadUI();
    });
    connect(m_ftpClient, &FtpManager::sigDownFileFinish, this, &MainWindow::slotDownTempFileFinish);

    if (m_connectInfo.deviceType == ConnectionService::DeviceType::PC) {
        // PC连接埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPcConn);
        m_url.setUrl("ftp://" + m_connectInfo.address + ":" + QString::number(FTP_SERVER_PORT));
    } else {
        // 安卓连接埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAndroidConn);

        if (m_connectInfo.connectType == ConnectionService::ConnectType::WIFI) {
            m_ftpClient->setTransferMode(QFtp::Active);
            m_url.setUrl("ftp://" + m_connectInfo.address + ":" + QString::number(WIFI_FTP_PORT));
        } else {
            m_ftpClient->setTransferMode(QFtp::Passive);
            m_url.setUrl("ftp://" + m_connectInfo.address + ":" + QString::number(USB_FTP_PORT));
        }
    }
    m_ftpClient->setUrl(m_url);
    m_isServerConnect = true;
    m_ftpClient->connectFtpServer();
}

void MainWindow::slotDisconnect()
{
    clearConnectionInfo();
    Q_EMIT sigDisconnect();
    m_isConnect = false;
    m_winFlage = WinFlage::DisconnectWin;
    m_uploadPath = "";
    m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
    m_titlebar->setBackground(true);
    m_mainStackedWin->setCurrentIndex(WinIndex::WinHomePage);
    deleteStackedWidget();
    deleteMobileListWidget();
    deleteTransmissionDialog();
    deleteSuspendTab();
    stopLoadUI();
    slotContinueSearch();
    if (m_isServerConnect) {
        disconnectService();
    }
    if (m_mobileFileList != nullptr) {
        m_mobileFileList->deleteLater();
        m_mobileFileList = nullptr;
    }
}

void MainWindow::slotNotFountApk()
{
    qCritical() << "kylin-assistant not installed!";
    QMessageBox msgBox;
    msgBox.setText(tr("Please install kylin-assistant on the Android terminal!"));
    msgBox.setIcon(QMessageBox::Critical);
}

void MainWindow::slotConnectFailed()
{
    qInfo() << "Failed to connect device!";
    if (m_isConnect) {
        setToolTipWin(tr("Connection error"), kdk::TipType::Error);
        slotDisconnect();
    } else {
        stopLoadUI();
        setToolTipWin(tr("Connection timed out"), kdk::TipType::Error);
    }
}

void MainWindow::slotFtpConnected()
{
    bool flag = mountFtp(m_url.toString(), m_url.userName(), m_url.password(), MOUNT_DIR);
    if (!flag) {
        slotMountError(true, "d-bus service fail!");
    }
    m_isMountFtp = true;
    Q_EMIT sigConnected(m_connectInfo.deviceName);
    if (m_connectInfo.deviceType == ConnectionService::DeviceType::PC) {
        // initPcSearchInfo();
        updateResult();
        slotCdMobileStorageDirectory("/");
    } else if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
        initMobileFileSync();
    }
}

void MainWindow::slotCurrentDirectoryList(const QMap<QString, FileInfo> &filelist)
{
    if (m_isDbusOperation) {
        // dbus操作
        Q_EMIT sigFileInfoList(filelist);
        m_isDbusOperation = false;
    } else {
        deleteMobileListWidget();
        QString deviceName = m_currentPath;
        if (m_currentPath == "/") {
            deviceName = m_connectInfo.deviceName;
        }
        if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
            m_mobileStorageWidget = new MobileStorageWidget(filelist, deviceName, TYPE::Mobile);
            m_mobileStorageWidget->setTheme(m_theme);
            connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
                m_storageMode = mode;
            });
            m_stackedMobileFileListWin->addWidget(m_mobileStorageWidget);
            m_stackedMobileFileListWin->setCurrentIndex(1);
            m_mobileStorageWidget->setMode(m_storageMode);
            connectMobileStorage();
        } else if (m_connectInfo.deviceType == ConnectionService::DeviceType::PC) {
            if (m_mobileFileList != nullptr) {
                m_mobileFileList->deleteLater();
                m_mobileFileList = nullptr;
            }
            m_mobileStorageWidget = new MobileStorageWidget(filelist, deviceName, TYPE::Pctopc);
            m_mobileStorageWidget->setTheme(m_theme);
            connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
                m_storageMode = mode;
            });
            m_stackedMobileFileListWin->addWidget(m_mobileStorageWidget);
            m_stackedMobileFileListWin->setCurrentIndex(0);
            m_mobileStorageWidget->setMode(m_storageMode);
            connectMobileStorage();
            // m_mainStackedWin->addWidget(m_mobileStorageWidget);
            // m_mainStackedWin->setCurrentIndex(2);
        }
    }
}

void MainWindow::slotTransferProgress(qint64 readBytes, qint64 totalBytes)
{
    if (!m_isDbusOperation) {
        if (m_transmissionDialog != nullptr) {
            m_transmissionDialog->setProgressBarRange(0, totalBytes);
            m_transmissionDialog->setProgressBarValue(readBytes);
            if (readBytes == totalBytes) {
                deleteTransmissionDialog();
                setToolTipWin(m_tipMesseage, kdk::TipType::Normal);
                if (!m_uploadPath.isEmpty()) {
                    m_currentPath = m_uploadPath;
                    m_ftpClient->cdToDir(m_uploadPath);
                    m_uploadPath = "";
                    startLoadUI();
                }
            }
        }
    } else {
        if (readBytes == totalBytes) {
            m_isDbusOperation = false;
        }
    }
}

void MainWindow::slotDownFileFinish(QString flag, QString filepath)
{
    if (!flag.isEmpty()) {
        // flag不为空，一个缩略图下载完成
        if (m_listItemWidget != nullptr) {
            m_listItemWidget->setThumbanil(filepath);
        }
    }
}

void MainWindow::slotDownAllFileFinish(QString flag)
{
    if (flag.isEmpty()) {
        // flag为空，信息文件下载完成
        qInfo() << "File information update completed!";
        updateResult();
    } else {
        // 缩略图全部下载完成
        qInfo() << "All thumbnails downloaded.";
    }
}

void MainWindow::slotDownTempFileFinish(QString filePath)
{
    stopLoadUI();
    if (m_isPcSearchInfo) {
        m_isPcSearchInfo = false;
        m_titlebar->onSearchInstalled(true, filePath);
    } else if (!filePath.isEmpty()) {
        FileInfo::fileOpen(filePath);
    } else {
        qInfo() << "Open file error, file path is null!";
    }
}

void MainWindow::slotDownFileFail(QString fileName, QString flag)
{
    Q_UNUSED(fileName);
    stopLoadUI();
    deleteTransmissionDialog();
    if (flag.isEmpty()) {
        slotConnectFailed();
    }
}

void MainWindow::slotDownFileFail(QString fileName)
{
    if (m_transmissionDialog != nullptr) {
        m_transmissionDialog->deleteLater();
        m_transmissionDialog = nullptr;
    }
    if (m_isPcSearchInfo) {
        m_isPcSearchInfo = false;
        m_titlebar->onSearchInstalled(false, fileName);
    }
    setToolTipWin(tr("file download failed"), kdk::TipType::Error);
}

void MainWindow::slotMountError(bool isMount, QString error)
{
    qInfo() << "mountFtpError:" << error;
    if (isMount) {
        QMessageBox::warning(this, tr("Warning"), tr("Peony access can be error-prone"), QMessageBox::Ok);
    } else {
        setToolTipWin(tr("Umount failed"), kdk::TipType::Warning);
    }
}

void MainWindow::slotAboutWinShow()
{
    // kylin-connectivity Version:
    m_aboutWindow =
        new kdk::KAboutDialog(this, QIcon::fromTheme("kylin-multi-collaboration"), QString(tr("kylin-connectivity")),
                              tr("Version:") + qApp->applicationVersion());
    m_aboutWindow->setAttribute(Qt::WA_DeleteOnClose);
    m_aboutWindow->setBodyText(tr("Mobile Assistant is an interconnection tool of Android device and Kirin operating "
                                  "system, which supports Android file synchronization, file transfer, screen "
                                  "mirroring and other functions, which is simple and fast to operate"));
    m_aboutWindow->setBodyTextVisiable(true);
    m_aboutWindow->setWindowModality(Qt::WindowModal);
    m_aboutWindow->setWindowModality(Qt::ApplicationModal);

    m_aboutWindow->show();
    m_aboutWindow->exec();
}

void MainWindow::slotAllDeviceInfo(const QMap<QString, KMobileCommon::DiscoveryDeviceInfo> &map)
{
    m_connectInterfaceWin->showLoad();
    m_connectInterfaceWin->setItemInfo(map);
}

void MainWindow::slotRequestReceived(PcScreenManage::ScreenMsg msg)
{
    switch (msg) {
    case PcScreenManage::ScreenMsg::SharingRequest: {
        // 投屏请求
        QString str1 =
            QString(tr("Received screen projection request from \"")) + m_connectInfo.deviceName + QString(tr("\""));
        QString str2 = QString(tr("After consent, the other party can share the device desktop to this screen."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-warning").pixmap(MSGICON_W, MSGICON_H));
        QPushButton *yesBtn = m_messageBox->addButton(QString(tr("YES")), QMessageBox::AcceptRole);
        QPushButton *noBtn = m_messageBox->addButton(QString(tr("NO")), QMessageBox::RejectRole);
        connect(m_messageBox, &QMessageBox::buttonClicked, this, [=](QAbstractButton *btn) {
            if (yesBtn == btn) {
                m_pcScreen->setConnectionRespond(true);
            } else {
                m_pcScreen->setConnectionRespond(false);
            }
            stopLoadUI();
        });
        m_messageBox->show();
        startTimer();
    } break;
    case PcScreenManage::ScreenMsg::RemoteRejection: {
        stopLoadUI();
        // 请求被拒绝
        QString str1 = QString(tr("The other party has refused your screen projection request!"));
        QString str2 = QString(tr("Failed to cast the screen. Please contact the other party and try again."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-error").pixmap(MSGICON_W, MSGICON_H));
        QPushButton *againBtn = m_messageBox->addButton(QString(tr("Again")), QMessageBox::AcceptRole);
        QPushButton *closeBtn = m_messageBox->addButton(QString(tr("Close")), QMessageBox::RejectRole);
        connect(m_messageBox, &QMessageBox::buttonClicked, this, [=](QAbstractButton *btn) {
            if (againBtn == btn) {
                // 重新连接
                m_pcScreen->connectService(m_connectInfo.address);
            }
        });
        m_messageBox->show();
    } break;
    case PcScreenManage::ScreenMsg::Successfully: {
        stopLoadUI();
        // 请求成功
        QString str1 = QString(tr("The other party agreed to your screen projection request!"));
        QString str2 = QString(tr("The screen is being cast, please wait..."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(QString(tr("OK")), QMessageBox::AcceptRole);
        m_messageBox->show();
    } break;
    case PcScreenManage::ScreenMsg::StartedScreen: {
        // 投屏启动
        stopLoadUI();
        if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::INITIATOR) {
            hide();
            m_suspendTabBar = new SuspendTabBar(SuspendTabBar::Display::Whole);
            connect(m_suspendTabBar, &SuspendTabBar::sigBtnClicked, this, &MainWindow::slotTabBtnClicked);
            m_suspendTabBar->setTheme(m_theme);
            m_suspendTabBar->showTabBar();
        }
    } break;
    case PcScreenManage::ScreenMsg::ScreenExit: {
        // 投屏退出
        deleteSuspendTab();
        show();
        if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::RECIPIENT && m_connectedWin != nullptr) {
            m_connectedWin->restoreScreenButton();
        }
        QString str1 = QString(tr("End of screen projection"));
        QString str2 = QString(tr("The other party has finished the screen projection function."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-error").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(QString(tr("OK")), QMessageBox::AcceptRole);
        m_messageBox->show();
    } break;
    case PcScreenManage::ScreenMsg::ScreenError: {
        // 投屏错误
        QString str1 = QString(tr("Screen projection loading error"));
        QString str2 =
            QString(tr("Please check whether to install the projection expansion package [kylin connectivity tools]"));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-error").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(QString(tr("CLOSE")), QMessageBox::AcceptRole);
        m_messageBox->show();
    } break;
    case PcScreenManage::ScreenMsg::Disconnect: {
        // 投屏断开
        deleteSuspendTab();
        disconnectScreen();
        show();
        QString str1 = QString(tr("End of screen projection"));
        QString str2 = QString(tr("The other party has finished the screen projection function."));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("dialog-error").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(QString(tr("OK")), QMessageBox::AcceptRole);
        m_messageBox->show();
    } break;
    case PcScreenManage::ScreenMsg::StartedControl: {
        // 进入反控
        // if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::INITIATOR && m_suspendTabBar == nullptr) {
        //     m_suspendTabBar = new SuspendTabBar(SuspendTabBar::Display::Part);
        //     connect(m_suspendTabBar, &SuspendTabBar::sigBtnClicked, this, &MainWindow::slotTabBtnClicked);
        //     m_suspendTabBar->setTheme(m_theme);
        //     m_suspendTabBar->setControlState(true);
        //     m_suspendTabBar->showTabBar();
        // }
    } break;
    case PcScreenManage::ScreenMsg::ExitControl: {
        // if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::RECIPIENT && m_suspendTabBar != nullptr) {
        //     // 暂时先模拟键盘退出
        //     QString common = "xdotool key ctrl+g";
        //     system(common.toUtf8().constData());
        //     // 退出反控
        //     m_suspendTabBar->setControlState(false);
        //     m_suspendTabBar->showTabBar();
        // } else if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::INITIATOR && m_suspendTabBar !=
        // nullptr) {
        //     m_suspendTabBar->setControlState(false);
        //     m_suspendTabBar->hideTabBar();
        // }
    } break;
    case PcScreenManage::ScreenMsg::HideView: {
        m_suspendTabBar->setDeskBtnState(true);
        show();
    } break;
    }
}

void MainWindow::onRecvSearchResult(QMap<QString, FileInfo> searchResult)
{
    qInfo() << "search by keyword";
    deleteMobileListWidget();
    m_mobileStorageWidget = new MobileStorageWidget(searchResult, "Search", TYPE::Search);
    m_mobileStorageWidget->setTheme(m_theme);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
        m_storageMode = mode;
    });
    m_stackedMobileFileListWin->addWidget(m_mobileStorageWidget);
    m_stackedMobileFileListWin->setCurrentIndex(1);
    m_mobileStorageWidget->setMode(m_storageMode);
    connectMobileStorage();
}

void MainWindow::slotUSBConnectOnClicked()
{
    m_connectionService->connectLocDev();
}

void MainWindow::setScreenOption()
{
    if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::RECIPIENT) {
        m_pcScreen->connectService(m_connectInfo.address);
    } else {
        if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
            if (m_deviceManage == nullptr) {
                m_deviceManage = new DeviceManage();
                connect(m_deviceManage, &DeviceManage::sigScreenConnected, this, [=]() {
                    stopLoadUI();
                });
                connect(m_deviceManage, &DeviceManage::sigSocketDisconnect, this, &MainWindow::slotExitMobileScreen);
            }
            if (m_connectionService->isSupportADB()) {
                BaseDevice::DeviceParams params;
                params.serial = m_connectionService->getDeviceSerial();
                params.maxFps = static_cast<quint32>(Config::getInstance().getMaxFps());
                params.localPort = USBPORT;
                params.screenIndex = getScreenIndex();
                m_deviceManage->connectDevice(params);
            } else {
                BaseDevice::DeviceParams params;
                params.serial = m_url.host();
                params.localPort = WIFIPORT;
                params.screenIndex = getScreenIndex();

                m_deviceManage->connectWifiDevice(params);
            }
        }
    }
}

void MainWindow::updateCurrentPath(int text)
{
    switch (text) {
    case PublicAttributes::MultType::QQPicture:
        m_currentPath = tr("QQPicture");
        break;
    case PublicAttributes::MultType::QQVideo:
        m_currentPath = tr("QQVideo");
        break;
    case PublicAttributes::MultType::QQMusic:
        m_currentPath = tr("QQMusic");
        break;
    case PublicAttributes::MultType::QQDoc:
        m_currentPath = tr("QQDocument");
        break;
    case PublicAttributes::MultType::WPicture:
        m_currentPath = tr("WeChatPicture");
        break;
    case PublicAttributes::MultType::WVideo:
        m_currentPath = tr("WeChatVideo");
        break;
    case PublicAttributes::MultType::WMusic:
        m_currentPath = tr("WeChatMusic");
        break;
    case PublicAttributes::MultType::WDoc:
        m_currentPath = tr("WeChatDocument");
        break;
    case PublicAttributes::MultType::Picture:
        m_currentPath = tr("Picture");
        break;
    case PublicAttributes::MultType::Video:
        m_currentPath = tr("Video");
        break;
    case PublicAttributes::MultType::Music:
        m_currentPath = tr("Music");
        break;
    case PublicAttributes::MultType::Doc:
        m_currentPath = tr("Document");
        break;
    case PublicAttributes::MultType::Wechat:
        m_currentPath = tr("WeChat");
        break;
    case PublicAttributes::MultType::QQ:
        m_currentPath = tr("QQ");
        break;
    case PublicAttributes::MultType::HomePage:
        m_currentPath = "Home page";
        break;
    default:
        break;
    }
}

void MainWindow::initPcSearchInfo()
{
    m_isPcSearchInfo = true;
    m_ftpClient->setTempPath(FILE_DOWN_PATH + m_connectInfo.uuid + "/");
    m_ftpClient->downFile(FILE_PATH_PCSEARCH);
    // ftp服务暂时不支持qt5的短连接请求，待修复
    // m_fileSyncManage = new FileSyncManage(m_connectInfo.uuid, m_url, this);
    // m_fileSyncManage->setSearchPath(FileSyncManage::SEARCH_TYPE::TYPE_PC, m_connectInfo.deviceName);
    // connect(m_fileSyncManage, SIGNAL(sigDownFileFail(QString, QString)), this,
    //         SLOT(slotDownFileFail(QString, QString)));
    // connect(m_fileSyncManage, &FileSyncManage::sigSearchInfoFinsh, m_titlebar, &Titlebar::onSearchInstalled);
    // connect(m_fileSyncManage, &FileSyncManage::sigTempFileDownFinish, this, &MainWindow::slotDownTempFileFinish);
    // m_fileSyncManage->downloadSearch();
}

void MainWindow::deleteTransmissionDialog()
{
    if (m_transmissionDialog != nullptr) {
        m_transmissionDialog->deleteLater();
        m_transmissionDialog = nullptr;
    }
}

void MainWindow::deleteStackedWidget()
{
    if (m_connectedWin != nullptr) {
        m_mainStackedWin->removeWidget(m_connectedWin);
        m_connectedWin->deleteLater();
        m_connectedWin = nullptr;
    }
}

void MainWindow::slotItemButtonClicked(int text)
{
    int tag = text;
    updateCurrentPath(text);
    qInfo() << "Clicked " << tag;
    deleteMobileListWidget();
    if (tag == PublicAttributes::MultType::QQPicture) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_PICTURE;
        initMobileListWidget(PublicAttributes::MultType::QQPicture);
    } else if (tag == PublicAttributes::MultType::QQVideo) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_VIDEO;
        initMobileListWidget(PublicAttributes::MultType::QQVideo);
    } else if (tag == PublicAttributes::MultType::QQMusic) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_MUSIC;
        initMobileListWidget(PublicAttributes::MultType::QQMusic);
    } else if (tag == PublicAttributes::MultType::QQDoc) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_QQ_DOCUMENT;
        initMobileListWidget(PublicAttributes::MultType::QQDoc);
    } else if (tag == PublicAttributes::MultType::WPicture) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_PICTURE;
        initMobileListWidget(PublicAttributes::MultType::WPicture);
    } else if (tag == PublicAttributes::MultType::WVideo) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_VIDEO;
        initMobileListWidget(PublicAttributes::MultType::WVideo);
    } else if (tag == PublicAttributes::MultType::WMusic) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_MUSIC;
        initMobileListWidget(PublicAttributes::MultType::WMusic);
    } else if (tag == PublicAttributes::MultType::WDoc) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_WECHAT_DOCUMENT;
        initMobileListWidget(PublicAttributes::MultType::WDoc);
    } else if (tag == PublicAttributes::MultType::Picture) {
        // 图片列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantPictureList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_PICTURE;
        initMobileListWidget(PublicAttributes::MultType::Picture);
    } else if (tag == PublicAttributes::MultType::Video) {
        // 视频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantVideoList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_VIDEO;
        initMobileListWidget(PublicAttributes::MultType::Video);
    } else if (tag == PublicAttributes::MultType::Music) {
        // 音频列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantAudioList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_MUSIC;
        initMobileListWidget(PublicAttributes::MultType::Music);
    } else if (tag == PublicAttributes::MultType::Doc) {
        // 文档列表埋点
        GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDocList);
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_DOCUMENT;
        initMobileListWidget(PublicAttributes::MultType::Doc);
    } else if (tag == PublicAttributes::MultType::Wechat || tag == PublicAttributes::MultType::QQ) {
        // QQ微信图片列表埋点
        if (tag == PublicAttributes::MultType::Wechat) {

            GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantWechatFileList);
        } else {
            GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantQQFileList);
        }
        m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
        //         m_winFlage = WIN_FLAGE::WIN_INIT_QQWECHAT;
        m_mobileFileSecondWidget = new MobileFileSecondWidget(text);
        QMap<QString, int> fileNumMap;
        m_fileSyncManage->getItemCount(fileNumMap);
        m_mobileFileSecondWidget->setItemCount(fileNumMap);
        //设置图片时间线的数据
        m_stackedMobileFileListWin->addWidget(m_mobileFileSecondWidget);
        m_loadAnimation = new LoadAnimation;
        m_loadAnimation->setHighLight();
        m_stackedMobileFileListWin->addWidget(m_loadAnimation);
        m_stackedMobileFileListWin->setCurrentIndex(m_fileSyncIndex);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigItemButtonClicked, this,
                &MainWindow::slotItemButtonClicked);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigShowMobileFileListWidget, this,
                &MainWindow::slotShowMobileFileListWidget);
        connect(m_mobileFileSecondWidget, &MobileFileSecondWidget::sigUpdateClicked, this,
                &MainWindow::slotItemButtonClicked);
        m_fileSyncManage->updateFileInfo(m_downFileType);
    }
}

void MainWindow::slotCdMobileStorageDirectory(QString path)
{
    // 手机存储列表埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantMobileStorage);
    m_currentPath = path;
    path.remove(m_connectInfo.deviceName);
    if (path.isEmpty()) {
        path = "/";
    }
    m_ftpClient->cdToDir(path);
    startLoadUI();
}

void MainWindow::slotContinueSearch()
{
    m_connectInterfaceWin->showLoad();
    m_discovery->stopDiscovery();
    m_discovery->startDiscovery();
}

void MainWindow::slotDownThumb()
{
    if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_FILE_NUM) {
        return;
    }
    if (m_listItemWidget != nullptr) {
        m_listItemWidget->setMode(m_classificationMode);
    }
    if (m_downFileType == FileSyncManage::LIST_TYPE::TYPE_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_VIDEO
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_QQ_VIDEO
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_PICTURE
        || m_downFileType == FileSyncManage::LIST_TYPE::TYPE_WECHAT_VIDEO) {
        m_fileSyncManage->downThumb(m_downFileType);
    }
}

void MainWindow::slotMenuFilePath(QString filePath)
{
    // 打开文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantOpenFile);
    if (m_connectInfo.deviceType == ConnectionService::DeviceType::PC) {
        m_ftpClient->setTempPath(FILE_DOWN_PATH + m_connectInfo.uuid + TEMP_DOWN_PATH);
        m_ftpClient->downFile(filePath);
    } else {
        m_fileSyncManage->downTempFile(filePath);
    }
    startLoadUI();
}

void MainWindow::slotSetLastWidget()
{
    Q_EMIT sigClearSearchLine();
    qInfo() << "search previous path" << m_currentPath;
    if (m_currentPath == "Home page") {
        slotShowMobileStorage();
    } else {
        if (m_currentPath == tr("Picture")) {
            slotItemButtonClicked(PublicAttributes::MultType::Picture);
        } else if (m_currentPath == tr("Video")) {
            slotItemButtonClicked(PublicAttributes::MultType::Video);
        } else if (m_currentPath == tr("Music")) {
            slotItemButtonClicked(PublicAttributes::MultType::Music);
        } else if (m_currentPath == tr("Document")) {
            slotItemButtonClicked(PublicAttributes::MultType::Doc);
        } else if (m_currentPath.startsWith(tr("WeChat"))) {
            slotItemButtonClicked(PublicAttributes::MultType::Wechat);
        } else if (m_currentPath.startsWith(tr("QQ"))) {
            slotItemButtonClicked(PublicAttributes::MultType::QQ);
        } else {
            slotCdMobileStorageDirectory(m_currentPath);
        }
    }
}

void MainWindow::slotShowMobileFileListWidget()
{
    m_fileSyncIndex = 2;
    // m_winFlage = WIN_FLAGE::WIN_RETURN_FILESYNC;
    m_fileSyncManage->abortDownThumb();
    deleteMobileListWidget();
    m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
    m_fileSyncManage->updateFileInfo(m_downFileType);
    m_loadAnimation = new LoadAnimation;
    m_loadAnimation->setHighLight();
    m_stackedMobileFileListWin->addWidget(m_loadAnimation);
    m_stackedMobileFileListWin->setCurrentIndex(2);
}

void MainWindow::uploadLocalListPath(QString itemName, const QStringList &localPath)
{
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantUploadFile);
    m_uploadPath = itemName;
    m_ftpClient->setTransferMode(QFtp::Passive);
    m_ftpClient->uploadAllFiles(localPath, itemName);
    m_tipMesseage = tr("Uploaded to") + itemName;
    initTransmissionDialog();
}

void MainWindow::slotLocalPathList(const QStringList &localPathList)
{
    // 上传文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantUploadFile);
    m_uploadPath = m_currentPath;
    m_ftpClient->setTransferMode(QFtp::Passive);
    m_ftpClient->uploadAllFiles(localPathList, m_currentPath);
    m_tipMesseage = tr("Uploaded to") + m_currentPath;
    initTransmissionDialog();
}

void MainWindow::slotShowMobileFileSecondWidget(int indexPath)
{
    m_fileSyncManage->abortDownThumb();
    m_fileSyncIndex = 3;
    slotItemButtonClicked(indexPath);
}

void MainWindow::slotShowMobileStorage()
{
    deleteMobileListWidget();
    m_currentPath = "Home page";
    if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
        m_stackedMobileFileListWin->setCurrentIndex(0);
    } else {
        int index = m_mainStackedWin->currentIndex();
        m_mainStackedWin->setCurrentIndex(index - 1);
        m_mainStackedWin->removeWidget(m_mainStackedWin->widget(index));
    }
}

void MainWindow::slotChooseFilePath(QString chooseFilePath, const QList<FileInfo> &selectFileNameList)
{
    qInfo() << "choose path" << chooseFilePath << "select file name list size" << selectFileNameList.size();
    QStringList listName;
    for (int i = 0; i < selectFileNameList.size(); i++) {
        listName << selectFileNameList.at(i).name();
    }
    qInfo() << "select file name list " << listName;
    if (listName.isEmpty()) {
        setToolTipWin(tr("file download failed"), kdk::TipType::Error);
        return;
    }
    // 下载文件埋点
    GenerateTools::buriedPoint(kabase::BuriedPoint::PT::KylinMobileAssistantDownloadFile);
    m_ftpClient->downAllFiles(selectFileNameList, chooseFilePath);
    m_tipMesseage = tr("Downloaded to") + chooseFilePath;
    initTransmissionDialog();
}

void MainWindow::slotAbortTransmission()
{
    m_ftpClient->abort();
    deleteTransmissionDialog();
    startLoadUI();
}

void MainWindow::initMobileFileSync()
{
    m_fileSyncManage = new FileSyncManage(m_connectInfo.uuid, m_url, this);
    connect(m_fileSyncManage, &FileSyncManage::sigDownFileFinish, this, &MainWindow::slotDownFileFinish);
    connect(m_fileSyncManage, &FileSyncManage::sigDownAllFileFinish, this, &MainWindow::slotDownAllFileFinish);
    connect(m_fileSyncManage, SIGNAL(sigDownFileFail(QString, QString)), this,
            SLOT(slotDownFileFail(QString, QString)));
    connect(m_fileSyncManage, &FileSyncManage::sigSearchInfoFinsh, m_titlebar, &Titlebar::onSearchInstalled);
    connect(m_fileSyncManage, &FileSyncManage::sigTempFileDownFinish, this, &MainWindow::slotDownTempFileFinish);
    m_downFileType = FileSyncManage::LIST_TYPE::TYPE_FILE_NUM;
    m_fileSyncManage->setSearchPath(FileSyncManage::SEARCH_TYPE::TYPE_ANDROID);
    m_fileSyncManage->updateFileInfo(m_downFileType);
}

void MainWindow::slotConnectBtnClicked()
{
    m_mainStackedWin->setCurrentIndex(WinIndex::WinConnect);
    m_connectInterfaceWin->setSearchBtnState(true);
}

int MainWindow::getScreenIndex()
{
    QDesktopWidget *desktopWidget = QApplication::desktop();
    for (int i = 0; i < desktopWidget->screenCount(); i++) {
        if (desktopWidget->screenGeometry(i).contains(this->geometry())) {
            return i;
        }
    }
}

void MainWindow::slotSearchInitFail()
{
    if (m_fileSyncManage != nullptr) {
        m_fileSyncManage->downloadSearch();
    }
}

void MainWindow::discInit()
{
    if (m_dbusInterface->isValid()) {
        qInfo() << "softbus init";
        m_dbusInterface->call("startDiscServer", DISC_SERVER_PATH);
    }
}

void MainWindow::slotInitDiscServerResult(bool flag)
{
    if (flag) {
        m_discClient = new QProcess(this);
        connect(m_discClient, &QProcess::started, this, [=]() {
            qInfo() << "softbus init success";
            GenerateTools::delayMs(500);
            m_discovery = new KMobileDiscovery::Discovery();
            connect(m_discovery, &KMobileDiscovery::Discovery::sigAllDeviceInfo, this, &MainWindow::slotAllDeviceInfo);
            m_discovery->startDiscovery();
        });
        connect(m_discClient, &QProcess::readyReadStandardError, this, [=]() {
            QString errOutput = m_discClient->readAllStandardError();
            qWarning() << "softbus client is not exist, softbus init failed." << errOutput;
        });
        m_discClient->start(DISC_CLIENT_PATH);
    } else {
        qWarning() << "softbus server init failed.";
    }
}

void MainWindow::deInitDisc()
{
    if (m_discovery != nullptr) {
        m_discovery->stopDiscovery();
        delete m_discovery;
        m_discovery = nullptr;
    }
    if (m_dbusInterface->isValid()) {
        qInfo() << "softbus deinit";
        m_dbusInterface->call("stopDiscServer");
    }
    if (m_discClient) {
        if (m_discClient->state() == QProcess::Running) {
            m_discClient->close();
        }
        delete m_discClient;
        m_discClient = nullptr;
    }
}

void MainWindow::slotReturnHomePage()
{
    m_mainStackedWin->setCurrentIndex(WinIndex::WinHomePage);
}

void MainWindow::slotConnectServiceUI(QString address)
{
    m_reconnectAddress = address;
    m_connectionService->startClient(address);
    QString str1 = QString(tr("Request sent successfully!"));
    QString str2 = QString(tr("The connection request has been sent to the selected device. Please click [YES] in "
                              "the opposite pop-up window"));
    m_messageBox = new QMessageBox(this);
    m_messageBox->setText(str1 + "\n" + str2);
    m_messageBox->setIconPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(MSGICON_W, MSGICON_H));
    m_messageBox->addButton(QString(tr("OK")), QMessageBox::AcceptRole);
    m_messageBox->show();
    startTimer();
}

void MainWindow::slotConnectedWinBtnClicked(ConnectedWin::BtnType type)
{
    switch (type) {
    case ConnectedWin::BtnType::Screen: {
        setScreenOption();
        QString str1 = QString(tr("Request sent successfully!"));
        QString str2 = QString(tr("The screen projection request has been sent to the connected device. Please click "
                                  "[Agree] in the opposite pop-up window"));
        m_messageBox = new QMessageBox(this);
        m_messageBox->setText(str1 + "\n" + str2);
        m_messageBox->setIconPixmap(QIcon::fromTheme("ukui-dialog-success").pixmap(MSGICON_W, MSGICON_H));
        m_messageBox->addButton(QString(tr("OK")), QMessageBox::AcceptRole);
        m_messageBox->show();
    } break;
    case ConnectedWin::BtnType::ExitScreen: {
        if (m_connectInfo.deviceRole == ConnectionService::DeviceRole::RECIPIENT) {
            slotExitPcScreen();
        } else {
            if (m_connectInfo.deviceType == ConnectionService::DeviceType::ANDROID) {
                slotExitMobileScreen();
            } else {
                slotExitPcScreen();
            }
        }
    } break;
    case ConnectedWin::BtnType::Disconnect: {
        slotDisconnect();
    } break;
    }
}


void MainWindow::slotExitMobileScreen()
{
    if (m_connectedWin != nullptr) {
        m_connectedWin->restoreScreenButton();
    }
    if (m_connectionService != nullptr) {
        m_connectionService->closeAbility();
    }
    if (m_deviceManage != nullptr) {
        m_deviceManage->deleteLater();
        m_deviceManage = nullptr;
    }
}

void MainWindow::slotExitPcScreen()
{
    if (m_connectedWin != nullptr) {
        m_connectedWin->restoreScreenButton();
    }
    deleteSuspendTab();
    if (m_pcScreen != nullptr) {
        m_pcScreen->disconnected();
    }
}

void MainWindow::slotTabBtnClicked(SuspendTabBar::BtnType type)
{
    switch (type) {
    case SuspendTabBar::BtnType::ControlBtn: {
        // if (m_suspendTabBar != nullptr) {
        //     m_suspendTabBar->hideTabBar();
        // }
        // 暂时先模拟键盘进入反控
        m_pcScreen->showCurtain();
        QString common = "xdotool key ctrl+h";
        system(common.toUtf8().constData());
        m_suspendTabBar->setDeskBtnState(false);
        // m_pcScreen->startedControl();
    } break;
    case SuspendTabBar::BtnType::ControlCloseBtn: {
        m_pcScreen->exitControl();
    } break;
    case SuspendTabBar::BtnType::ReturnDesktopBtn: {
        m_pcScreen->hideCurtain();
        show();
    } break;
    case SuspendTabBar::BtnType::ScreenShareBtn: {
        m_pcScreen->showCurtain();
        hide();
    } break;
    case SuspendTabBar::BtnType::ExitBtn: {
        slotExitPcScreen();
        show();
    } break;
    }
}

void MainWindow::deleteSuspendTab()
{
    if (m_suspendTabBar != nullptr) {
        delete m_suspendTabBar;
        m_suspendTabBar = nullptr;
    }
}

void MainWindow::connectMobileFileList()
{
    connect(m_mobileFileList, &MobileFileList::sigPictureClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigVideoClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigMusicClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigDocumentClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigWeChatClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigQQClicked, this, &MainWindow::slotItemButtonClicked);
    connect(m_mobileFileList, &MobileFileList::sigMobileStorageClicked, this,
            &MainWindow::slotCdMobileStorageDirectory);
}

void MainWindow::connectMobileStorage()
{
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigFileName, this, &MainWindow::slotCdMobileStorageDirectory);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigShowMobileStorage, this,
            &MainWindow::slotShowMobileStorage);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigCurrentIndexPath, this,
            &MainWindow::slotCdMobileStorageDirectory);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigLocalPathList, this, &MainWindow::slotLocalPathList);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigUpdateClicked, this,
            &MainWindow::slotCdMobileStorageDirectory);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigMenuFileName, this, &MainWindow::slotMenuFilePath);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigSetLastWidget, this, &MainWindow::slotSetLastWidget);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigChooseFilePath, this, &MainWindow::slotChooseFilePath);
    connect(m_mobileStorageWidget, &MobileStorageWidget::sigModeChange, this, [=](QListView::ViewMode mode) {
        m_storageMode = mode;
    });
    m_mobileStorageWidget->setMode(m_storageMode);
}
